import 'dart:async';

import 'package:app/services/address.dart';
import 'package:app/services/dio_manager.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:get/get_utils/src/get_utils/get_utils.dart';
import 'package:dio/dio.dart';

import '../common/colors.dart';
class CountdownButton extends StatefulWidget {

  // const CountdownButton({Key? key}) : super(key: key);
  var _username;
  var type;
  CountdownButton(this._username,{this.type='login'});

  @override
  State<CountdownButton> createState() => _CountdownButtonState();
}

class _CountdownButtonState extends State<CountdownButton> {

  late Timer timer;

  int countdownTime = 0;

  /// 倒计时
  ///
  void startCountdownTimer() {

    countdownTime = 59;

    const oneSec = Duration(seconds: 1);

    // var callback = (timer) => {
    //   if (countdownTime < 1)
    //     {timer.cancel()}
    //   else {
    //     // countdownTime = countdownTime - 1
    //     countdownTime--
    //     }
    //
    // };

    timer = Timer.periodic(oneSec, (timer){
      setState(() {
          if (countdownTime < 1) {
            timer.cancel();
            }
          else {
            countdownTime--;
          }
      });
    });


  }

  /// 发送验证码点击
  void sendCodeClick() {
    if (countdownTime == 0) {
      countdownTime = 59;
      startCountdownTimer();
    }
  }

  ///发送验证码;
  requestDataSendCode(var phoneStr)async{

    print(widget.type);
    print(phoneStr.replaceAll(new RegExp(r"\s+\b|\b\s"), ""));

    var params = FormData.fromMap({
      'mobile': phoneStr.replaceAll(new RegExp(r"\s+\b|\b\s"), ""),
      'type': '${widget.type}',
    });

    var json = await DioManager().
    kkRequest(Address.sendCode,bodyParams: params,isShowLoad: true);

    if(json['errmsg']=='ok'){
      sendCodeClick();
    }

    BotToast.showText(text: '${json['message']}');

    // DioManager().rcRequset('/api/v1/login/0',params:params).then((value){

    //   BotToast.showText(text: '${value['message']}');
    //
    // });
  }



  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(right: 15),
      width: 76,
      height: 30,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: AppColor.themeColor,
        borderRadius: BorderRadius.all(Radius.circular(14)),
      ),
      child: GestureDetector(
        child:Text(
          countdownTime > 0 ? '重新发送($countdownTime)' : '获取验证码',
          style: TextStyle(
            color: countdownTime > 0?Colors.white:Colors.white, fontSize: 12,),
        ),
        onTap: () {

          if (!GetUtils.isPhoneNumber(widget._username.text)) {
            // Toast.toast(context,msg: '请输入正确的手机号码');
            BotToast.showText(text: '请输入正确的手机号码');
            return;
          }
          if(widget._username.text.isEmpty){
            BotToast.showText(text: '请输入正确的手机号码');
            return;
          }

          requestDataSendCode(widget._username.text);

          // requestDataSendCode(widget._username.text).then((
          //     json) {
          //   BotToast.showText(text: json['message']);
          //   BotToast.closeAllLoading();
          //
          //
          //   // startCountdownTimer();
          //   // if(_countdownTime== 0){
          //   //
          //   //   setState(() {
          //   //     _countdownTime = 59;
          //   //   });
          //   //
          //   // }
          //
          // });
        },
      ),

    );
  }
}
